package com.douwong.student.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.douwong.student.R;
import com.douwong.student.adapter.ClassTestAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.ClassBaseActivity;
import com.douwong.student.contant.Config;
import com.douwong.student.enums.E_CommandType;
import com.douwong.student.enums.E_Destination;
import com.douwong.student.fragment.FillFragment;
import com.douwong.student.fragment.JudgeFragment;
import com.douwong.student.fragment.MultiChoiceFragment;
import com.douwong.student.fragment.SingleChoiceFrgment;
import com.douwong.student.interfaces.ClassTestInterface;
import com.douwong.student.model.ResTestProblemsInfo;
import com.douwong.student.model.TestInfos;
import com.douwong.student.popuwindow.SubmitDialog;
import com.douwong.student.socket.LTPServer;
import com.douwong.student.utils.CommonPlaneCommit;
import com.douwong.student.utils.JsonUtils;
import com.douwong.student.utils.ToastUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @autor yichao
 * @time 2017/4/514:08
 * @des 课堂测试
 */
public class ClassTestActivity extends ClassBaseActivity implements ViewPager.OnPageChangeListener{
    public static boolean isShown =false;
    private TextView mTextTotalScore, mTextAnswer, mTextTitlePic;
    private RelativeLayout mRlRootView;
    private ImageButton mImageButtonSubmit;
    private ImageView mImagePeople,mImagePlane;
    private ViewPager mViewPager;
    private LinearLayout mLlTitelPage;
    private List<Map<String,Object>> mMapList;
    private String[] titileType = new String[]{"单选题", "多选题", "判断题", "填空题"};
    private List<TestInfos> mTestInfosList;
    private boolean isCommit;
    private int[] planes = {R.mipmap.plane_1, R.mipmap.plane_2, R.mipmap.plane_3};
    private CommonPlaneCommit mPlaneCommit;

    @Override
    protected void initView() {
        setContentView(R.layout.classtest_activity);
        mRlRootView = (RelativeLayout) findViewById(R.id.rl_root);
        mTextTotalScore = (TextView) findViewById(R.id.tv_total_score);
        mImageButtonSubmit = (ImageButton) findViewById(R.id.ib_submitButton_quizzes);
        mImagePeople = (ImageView) findViewById(R.id.iv_people);
        mImagePlane = (ImageView) findViewById(R.id.iv_plane_quizzes);
        mViewPager = (ViewPager) findViewById(R.id.viewpage);
        mTextAnswer = (TextView) findViewById(R.id.tv_lastAnswer);
        mLlTitelPage = (LinearLayout) findViewById(R.id.ll_Title_Page);
        mTextTitlePic = (TextView) findViewById(R.id.tv_Title_pic);
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        mImageButtonSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //提交答案
                if (!BaseApplication.isTeaching) {
                    ToastUtils.makeText(ClassTestActivity.this,"教师不在线");
                    return;
                }

                loadResult();
                String content = "";
                if (BaseApplication.noDoTestSum > 0) {
                    content = "还有" + BaseApplication.noDoTestSum + "题没有作答,确定提交吗？";
                } else {
                    content = "确定提交吗？";
                }
                SubmitDialog submitDialog = SubmitDialog.getInstance();
                submitDialog.ShowSubmitDialog(ClassTestActivity.this, content);
                submitDialog.setMClick(new SubmitDialog.MonClick() {
                    @Override
                    public void confireClick() {
                        submitAnswer();
                    }

                    @Override
                    public void cancelClick() {
                        //取消
                        isCommit = false;
                        BaseApplication.noDoTestSum = 0;

                    }
                });
            }
        });
    }
    /**
     *提交答案
     */
    private void submitAnswer() {

        //提交
        isCommit = true;
        BaseApplication.noDoTestSum = 0;
        //设置提交后状态
        changeCommitStatu();
        mImageButtonSubmit.setSelected(true);
        mImageButtonSubmit.setClickable(false);
        //飞机
       LTPServer.createInstance(this).sendMsg(mTestInfosList, E_CommandType.testSubmit, E_Destination.teacher,new int[]{BaseApplication.sTeacherOnline.teacher.teacherId});

        planeColor();

    }
    /**
     * 飞机随机出现颜色
     */
    public void planeColor() {
        Random random = new Random();
        int pick = random.nextInt(planes.length);
        mImagePlane.setBackgroundResource(planes[pick]);
        mImagePlane.setVisibility(View.VISIBLE);// 执行飞机动画
        mImagePlane.startAnimation(mPlaneCommit.getAnimationSet());
    }

    /**
     * 设置提交后Fragment的状态
     */
    private void changeCommitStatu() {

        for (Map<String, Object> mList : mMapList) {
            ClassTestInterface classTestInterface = (ClassTestInterface) mList.get(Config.FRAGMENT);
            classTestInterface.setCommitStatue();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        mPlaneCommit = new CommonPlaneCommit(this, mImagePlane, width, height);
        mTestInfosList = new ArrayList<>();
        isShown=true;
        registerReceiver(mReceiver,mIntentFilter);
    }
    IntentFilter mIntentFilter=new IntentFilter(){
        {
            addAction(Config.SEND_TEST);
            addAction(Config.TEST_COLLECT);
            addAction(Config.TEACHER_LEAVE_CLASS);
            addAction(Config.LOGIN_CLASS_FAILURE);
            addAction(Config.CLASS_TEST_FINSH);
        }
    };
    BroadcastReceiver mReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Config.SEND_TEST:
                    String stringExtra = intent.getStringExtra(Config.INTENT_DATA);
                    logcatI(stringExtra);
                    ResTestProblemsInfo resTestProblemsInfo = JsonUtils.parseString(stringExtra, ResTestProblemsInfo.class);
                    if (resTestProblemsInfo!=null){
                    fragmentClassfy(resTestProblemsInfo.getTopicItem());
                    ClassTestAdapter classTestAdapter = new ClassTestAdapter(getSupportFragmentManager(), mMapList);
                    mViewPager.setAdapter(classTestAdapter);
                    mViewPager.setOffscreenPageLimit(mMapList.size());
                    mViewPager.addOnPageChangeListener(ClassTestActivity.this);
                    itemNumberDisplay(mMapList.size());
                    showItem(0);
                }else {
                    ToastUtils.makeText(ClassTestActivity.this,"获取测试数据失败");
                    finish();
                }
                    break;
                case Config.TEST_COLLECT:
                    //收取答案
                    if (isCommit){
                        finish();
                        return;
                    }
                    LTPServer.createInstance(ClassTestActivity.this).sendMsg(mTestInfosList, E_CommandType.testSubmit, E_Destination.teacher,new int[]{BaseApplication.sTeacherOnline.teacher.teacherId});
                    finish();
                    break;
                case Config.TEACHER_LEAVE_CLASS:
                case Config.LOGIN_CLASS_FAILURE:
                case Config.CLASS_TEST_FINSH:
                    finish();

                    break;

            }


        }
    };

    /**
     * 获取答案
     */
    private void loadResult() {
        mTestInfosList.clear();
        for (Map<String, Object> mList : mMapList) {
            ClassTestInterface classTestInterface = (ClassTestInterface) mList.get(Config.FRAGMENT);
            TestInfos answerInfo = classTestInterface.getAnswerInfo();
            mTestInfosList.add(answerInfo);

        }

    }

    public static  void startActivity(Context context){
        Intent intent=new Intent(context,ClassTestActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isShown=false;
        if (mReceiver!=null){
            unregisterReceiver(mReceiver);
            mReceiver=null;
        }
    }
    /**
     * fragment分类
     *
     * @param topicItem 试题数据
     */
    private void fragmentClassfy(List<ResTestProblemsInfo.TopicItemBean> topicItem) {
        mMapList = new ArrayList<>();
        Map<String, Object> objectMap = null;
        for (int i = 0; i < topicItem.size(); i++) {
            //重组数据
            int itemType = topicItem.get(i).getTopicType().getItemType();
            switch (itemType) {
                case 1:
                    //单项选择
                    objectMap = new HashMap<>();
                    objectMap.put(Config.FRAGMENT, new SingleChoiceFrgment(this, topicItem.get(i)));
                    objectMap.put(Config.TOPICTYPE, topicItem.get(i).getTopicType().getTypeName());
                    mMapList.add(objectMap);
                    break;
                case 2:
                    //多项选择
                    objectMap = new HashMap<>();
                    objectMap.put(Config.FRAGMENT, new MultiChoiceFragment(this, topicItem.get(i)));
                    objectMap.put(Config.TOPICTYPE, topicItem.get(i).getTopicType().getTypeName());
                    mMapList.add(objectMap);
                    break;
                case 3:
                    //填空
                    objectMap = new HashMap<>();
                    objectMap.put(Config.FRAGMENT, new FillFragment(this, topicItem.get(i)));
                    objectMap.put(Config.TOPICTYPE, topicItem.get(i).getTopicType().getTypeName());
                    mMapList.add(objectMap);

                    break;
                case 15:
                    //判断题
                    objectMap = new HashMap<>();
                    objectMap.put(Config.FRAGMENT, new JudgeFragment(this, topicItem.get(i)));
                    objectMap.put(Config.TOPICTYPE, topicItem.get(i).getTopicType().getTypeName());
                    mMapList.add(objectMap);
                    break;
            }
        }
    }
    /**
     * 提交按钮和题目类型
     *
     * @param currentPage
     */
    @SuppressWarnings("deprecation")
    private void showItem(int currentPage) {
        mViewPager.setCurrentItem(currentPage);
        mTextTitlePic.setBackgroundDrawable(setTitlePicByTitle((String) mMapList.get(currentPage).get(Config.TOPICTYPE)));
        //		showFragment(mNavData.get(currentPage - 1));
        for (int j = 0; j < mMapList.size(); j++) {
            mLlTitelPage.getChildAt(j).setBackgroundResource(R.mipmap.not_to_do);
        }
        mLlTitelPage.getChildAt(currentPage).setBackgroundResource(R.mipmap.used_do);
        if (currentPage == mMapList.size() - 1) {
            mImageButtonSubmit.setVisibility(View.VISIBLE);
        } else {
            mImageButtonSubmit.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 设置题目类型
     * @param title
     * @return
     */
    private Drawable setTitlePicByTitle(String title) {
        Drawable drawable = null;
        if (title.equals(titileType[0])) {// 单选
            drawable = getResources().getDrawable(R.mipmap.radiobuttonlistpic);
        } else if (title.equals(titileType[1])) {// 多选
            drawable = getResources().getDrawable(R.mipmap.multiple_choice_question_pic);
        } else if (title.equals(titileType[2])) {// 判断题
            drawable = getResources().getDrawable(R.mipmap.judgment_questions_pic);
        } else if (title.equals(titileType[3])) {// 填空
            drawable = getResources().getDrawable(R.mipmap.fil_the_blanks_pic);
        }
        return drawable;
    }

    /**
     * 下方页数控件显示
     *
     * @param itemSize
     */
    public void itemNumberDisplay(int itemSize) {
        mLlTitelPage.removeAllViews();
        for (int i = 0; i < itemSize; i++) {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            lp.leftMargin = 15;
            final TextView textView = new TextView(ClassTestActivity.this);
            if (i == 0) {
                textView.setBackgroundResource(R.mipmap.used_do);
            } else {
                textView.setBackgroundResource(R.mipmap.not_to_do);
            }
            textView.setLayoutParams(lp);
            textView.setGravity(Gravity.CENTER);
            textView.setText((i + 1) + "");
            textView.setTextSize(25);
            mLlTitelPage.addView(textView);
            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int currentPage = Integer.parseInt(((TextView) v).getText().toString()) - 1;
                    try {
                        showItem(currentPage);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        showItem(position);

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}
